<template>
  <div class="search">
    <a-row>
      <a-col :flex="1">
        <a-form
          :model="formModel"
          :label-col-props="labelColProps"
          :wrapper-col-props="wrapperColProps"
          label-align="left"
        >
          <a-row :gutter="16">
            <template v-for="(item, index) in fileds" :key="index">
              <a-col :span="item.span">
                <a-form-item :field="item.field" :label="item.label">
                  <component
                    :is="item.tag"
                    v-model="formModel[item?.field || 'key']"
                    :placeholder="item.placeholder"
                    v-bind="item.attrs"
                  >
                  </component>
                </a-form-item>
              </a-col>
            </template>
            <a-col :flex="'170px'">
              <a-row justify="space-between">
                <a-col :span="9">
                  <a-button type="primary" @click="search">
                    <template #icon>
                      <icon-search />
                    </template>
                    搜索
                  </a-button>
                </a-col>
                <a-col :span="9">
                  <a-button @click="reset">
                    <template #icon>
                      <icon-refresh />
                    </template>
                    重置
                  </a-button>
                </a-col>
              </a-row>
            </a-col>
          </a-row>
        </a-form>
      </a-col>
    </a-row>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, PropType, defineExpose } from 'vue';
  import { Filed } from './types';

  // 定义 props
  const props = defineProps({
    fileds: {
      type: Array as PropType<Filed[]>,
      default() {
        return [];
      },
    },
    labelColProps: {
      type: Object,
      default: () => {
        return {
          span: 6,
        };
      },
    },
    wrapperColProps: {
      type: Object,
      default: () => {
        return {
          span: 18,
        };
      },
    },
  });
  // 定义emit
  const emit = defineEmits(['search', 'reset']);
  const formModel: any = reactive({
    ...Object.fromEntries(
      props.fileds.map((item) => [item.field, item.initValue])
    ),
  });
  //
  // 点击搜索
  const search = () => {
    emit('search', formModel);
  };
  // 重置
  const reset = () => {
    const keys = Object.keys(formModel);
    keys.forEach((element) => {
      const temp =
        props.fileds.find((item) => item.field === element)?.initValue || null;
      formModel[element] = temp;
    });
    emit('reset', formModel);
  };
  defineExpose({
    search,
  });
</script>

<style lang="less" scoped>
  .search {
    padding: 0 10px;
  }
</style>
